package com.demo.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.apache.log4j.Logger;

import java.net.InetAddress;
import java.net.InetSocketAddress;

import static io.netty.handler.codec.http.HttpHeaderUtil.is100ContinueExpected;
import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by carl on 16/5/29.
 */
public class HttpServerHandler  extends SimpleChannelInboundHandler<Object> {
    private static final Logger logger = Logger.getLogger(HttpServerHandler.class);

    private HttpRequest request;
    private QueryStringDecoder queryStringDecoder;
    private String uri;
    private String postContent;
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //cause.printStackTrace();
        logger.error(cause.getMessage());
        ctx.close();
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
    //接收消息,并处理消息和业务逻辑的地方.
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Object msg){
        InetAddress remoteAddr = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress();
        int remotePort = ((InetSocketAddress)ctx.channel().remoteAddress()).getPort();
        String remoteIp=remoteAddr.getHostAddress();
        if (msg instanceof HttpRequest) {

            HttpRequest request = this.request = (HttpRequest) msg;
            if (is100ContinueExpected(request)) {
                send100Continue(ctx);
            }
            //netty 5 A2的方法，可能正式版的方法名不叫uri();
            uri = request.uri();
            System.out.println("请求的uri：" + uri);
            queryStringDecoder = new QueryStringDecoder(request.uri());
            System.out.println("请求传递过来的参数:" + queryStringDecoder.parameters().toString());
        }
        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf content = httpContent.content();
            if (msg instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) msg;
                if (content.isReadable()) {
                    postContent = content.toString(CharsetUtil.UTF_8);
                    if (postContent != null || postContent.length() > 0) {
                        postContent = postContent.substring(1, postContent.length() - 1);
                        System.out.println("post请求传递过来的参数:" + postContent);
                    }
                }
                //使用if去判断截取的uri，根据uri的不同进入不同的方法，然后根据不同的方法确定不同方法需要的请求参数是在postContent中还是在queryStringDecoder中
                //如果在postContent需要把它转换成json
                //如果是在queryStringDecoder中则需要queryStringDecoder.parameters()把它转换成list，
                //获得参数之后就可以进行真正的业务处理了。
            }
        }
    }

    private void send100Continue(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, CONTINUE);
        ctx.write(response);
    }
}
